import React from 'react';
import md5 from 'js-md5';
import InputItem from 'antd-mobile/lib/input-item';
import List from 'antd-mobile/lib/list';
import Button from 'antd-mobile/lib/button';
import Toast from 'antd-mobile/lib/toast';
import Modal from 'antd-mobile/lib/modal';
import fetchJsonp from 'fetch-jsonp';
import BackNav from 'shared/components/BackNav';
import Icon from 'shared/components/base/Icon';
import localStorage from 'shared/utils/localStorage';
import { getEditPhoneApi, getEditPasswordApi } from 'shared/api/index';
import getUrlParam from 'shared/utils/getUrlParam';
import {
  registerApi, forgotPasswordApi,
  sendVerifyCodeApi, getImageverifyCodeApi, authForgotPasswordApi,
  encryptPhoneApi
} from '../api';

import './index.less';

const alert = Modal.alert;

const inputIcon = require('src/static/inputIcon.png');

const forgetFormLable = {
  title: '忘记密码',
  passwordLabel: '新密码',
  buttonLabel: '确认修改'
}

const registerFormLable = {
  title: '用户注册',
  passwordLabel: '设置密码',
  buttonLabel: '立即注册'
}

export default class Form extends React.PureComponent {
  constructor(props) {
    super(props)

    this.data = {}
    this.state = {
      verifyCode: '',
      timer: 60,
      flag: true,
      msg: '获取手机验证码'
    }
  }

  componentDidMount() {
    this.getImageverifyCode();
  }

  getImageverifyCode = () => {
    getImageverifyCodeApi({ sess_id: localStorage.get('sessId') }).then(({code, data}) => {
      if (code === 1000) {
        this.setState({ verifyCode: data.base64codeimage });
      }
    })
  }

  hanldeChange = (key, value) => {
    this.data[key] = value;
  }

  hanldeGetVerifyCode = () => {
    if (!this.state.flag) {
      return;
    }
    if (this.data.mobile.length < 11) {
      Toast.success('手机号码必须为11位', 1)
      return;
    }

    this.single = true;
    if (!this.single) {
      return;
    }
    const { isRegisterForm, isEditPhone } = this.props;
    let state = 'resetPassword';
    if (isRegisterForm) {
      state = 'register'
    }
    if (isEditPhone) {
      state = 'bindMobile'
    }

    if (getUrlParam('auth')) {
      state = getUrlParam('auth');
    }

    sendVerifyCodeApi({
      mobile: this.data.mobile,
      verifycode: this.data.verifyImgcode,
      state
    }).then((result) => {
      if (result.code === 1000) {
        Toast.success('获取成功')
        this.single = false;
        let { timer } = this.state;
        const getVerifyTimer = setInterval(() => {
          if (timer > 0) {
            this.setState({ timer: timer--, msg: `${timer}S后获取`, flag: false })
          } else {
            clearInterval(getVerifyTimer);
            this.setState({ timer: 60, msg: '获取手机验证码', flag: true })
          }
        }, 1000)
      } else if (result.code === 1002) {
        const { pathname } = __self.history.location
        if (getUrlParam('auth') !== 'auth' && pathname !== '/forgetPassword') {
          if (+result.data.result.code === 30019 || +result.data.result.code === 30018 || +result.data.result.code === 20012) {
            __self.history.push('/Login?resetPassword=true')
          }
        } else {
          Toast.fail(result.data.result.message);
        }
      } else {
        if (result.info === 'ACCOUNT 已存在') {
          Toast.fail('该账号已经存在');
        } else {
          Toast.fail(result.info);
        }
      }
    })
  }

  editPasswordApi() {
    if (this.data.password == this.data.repassword) {
      return Toast.fail('两次密码不一致');
    }
    const password = md5(`${this.data.password}`)
    const data = localStorage.getObject('loginData');
    encryptPhoneApi({ plaintext: +data.mobile }).then(({ data }) => {
      fetchJsonp(getEditPasswordApi({
        account: data.encrypttext,
        old_password: md5(`${this.data.oldpassword}`),
        password: password,
        repassword: password,
      }))
        .then(function (response) {
          return response.json()
        })
        .then(function (res) {
          if (res.code === 1) {
            __self.history.push('/account/person-details')
          } else {
            Toast.fail(res.message, 1)
          }
        })
    })
  }

  handleSubmit = () => {
    const { isRegisterForm, isEditPhone, isEditPasswordForm } = this.props;
    let request = forgotPasswordApi;
    const message = {
      success: '调用接口成功',
      fail: '修改失败'
    }
    if (getUrlParam('auth')) {
      request = authForgotPasswordApi
    }
    if (isEditPasswordForm) {
      this.editPasswordApi();
      return;
    }

    if (isRegisterForm) {
      request = registerApi;
      message.success = "注册成功"
      message.fail = "注册失败"
    }

    if (isEditPhone) {
      encryptPhoneApi({ plaintext: this.data.mobile }).then(({ data }) => {
        fetchJsonp(getEditPhoneApi({
          account: data.encrypttext,
          sms_code: this.data.verifycode,
          sessionid: localStorage.get('sessId'),
        }))
          .then(function (response) {
            return response.json()
          })
          .then(function (res) {
            if (res.code === 1) {
              __self.history.push('/account/person-details')
            } else {
              Toast.fail(res.message, 1)
            }
          })
      })
      return;
    }

    request(this.data).then((result) => {
      if (result.code === 1000) {
        if (!isRegisterForm) {
          alert('调用接口成功', '', [
            {
              text: '确定', onPress: () => {
                __self.history.push('/')
              }
            },
          ]);
          return;
        }
        __self.history.push('/')
      } else {
        if (result.info) {
          Toast.fail(result.info)
        } else {
          Toast.fail(message.fail)
        }
      }
    })
  }

  render() {
    const { isRegisterForm, isEditPhone, isEditPasswordForm } = this.props;
    const { verifyCode, msg } = this.state;
    let label = forgetFormLable;
    if (isRegisterForm) {
      label = registerFormLable;
    } else if (isEditPhone) {
      label = {
        buttonLabel: '提交',
        title: '变更绑定手机号'
      }
    }

    return (
      [
        <BackNav key="formBackNav" to="/" />,
        <div className="login-module-form" key="login-module-form">
          <div className="login-module-form-title">
            <span>{isEditPasswordForm ? '修改密码' : label.title}</span>
          </div>

          <div className="login-module-form-content">
            <List>

              {
                !isEditPasswordForm &&
                <div>
                  <InputItem
                    type="number"
                    maxLength={11}
                    onChange={(value) => this.hanldeChange('mobile', value)}
                  >
                    <div className="login-module-label">
                      <span>手机号码</span>
                      <span className="label-icon">
                        <Icon type="wode" />
                        <img src={inputIcon} alt='' />
                      </span>
                    </div>
                  </InputItem>
                  <div className="login-module-confilm">
                    <InputItem
                      onChange={(value) => this.hanldeChange('verifyImgcode', value)}
                    >
                      <div className="login-module-label">
                        <span>验证码</span>
                        <span className="label-icon">
                          <span className="iconfont ase-label">ASE</span>
                          <img src={inputIcon} alt='' />
                        </span>
                      </div>
                    </InputItem>
                    <div className="login-module-confilm-code">
                      <img src={verifyCode} alt='' />
                    </div>
                    <div className="login-module-confilm-text" onClick={this.getImageverifyCode}>看不清？换一张</div>
                  </div>
                  <div className="login-module-msg">
                    <InputItem
                      onChange={(value) => this.hanldeChange('verifycode', value)}
                    >
                      <div className="login-module-label">
                        <span>短信验证码</span>
                        <span className="label-icon">
                          <Icon type="youjianxinjian" />
                          <img src={inputIcon} alt='' />
                        </span>
                      </div>
                    </InputItem>
                    <div className="login-module-msg-btn" onClick={this.hanldeGetVerifyCode}>{msg}</div>
                  </div>
                </div>
              }

              {
                isEditPasswordForm &&
                <InputItem
                  type="password"
                  key="oldPassword"
                  onChange={(value) => this.hanldeChange('oldpassword', value)}
                >
                  <div className="login-module-label">
                    <span>旧密码</span>
                    <span className="label-icon">
                      <Icon type="suo" />
                      <img src={inputIcon} alt='' />
                    </span>
                  </div>
                </InputItem>
              }
              {
                !isEditPhone &&
                ([
                  <InputItem
                    type="password"
                    key="password"
                    onChange={(value) => this.hanldeChange('password', value)}
                  >
                    <div className="login-module-label">
                      <span>{label.passwordLabel}</span>
                      <span className="label-icon">
                        <Icon type="suo" />
                        <img src={inputIcon} alt='' />
                      </span>
                    </div>
                  </InputItem>,
                  <InputItem
                    type="password"
                    key="repassword"
                    onChange={(value) => this.hanldeChange('password2', value)}
                  >
                    <div className="login-module-label">
                      <span>确认密码</span>
                      <span className="label-icon">
                        <Icon type="suo" />
                        <img src={inputIcon} alt='' />
                      </span>
                    </div>
                  </InputItem>
                ])
              }
            </List>

            <Button className="form-btn" type="warning" onClick={this.handleSubmit}>{label.buttonLabel}</Button>
          </div>
        </div>
      ]

    )
  }
}
